
<!--src\views\PermissionManagement.vue-->
<template>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <div class="header-content">
                <div class="title-section">
                    <h1 class="page-title">权限管理系统</h1>
                    <div class="divider"></div>
                    <span class="subtitle">Total: {{ totalItems }}</span>
                </div>
                <div class="action-group">
                    <el-input
                        v-model="searchKeyword"
                        placeholder="输入权限名称/标识"
                        clearable
                        @input="handleSearch"
                        class="search-input"
                        size="large"
                    >
                        <template #prefix>
                            <el-icon class="search-icon"><Search /></el-icon>
                        </template>
                    </el-input>
                    <el-button type="primary" size="large" @click="handleCreate">
                        <el-icon><Plus /></el-icon>
                        新建权限
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表格内容 -->
        <div class="table-container">
            <el-table
                :data="pageData"
                style="width: 100%"
                size="medium"
                stripe
                :cell-style="{ padding: '8px 12px' }"
                :header-cell-style="{ background: '#f8fafc', padding: '8px 12px', position: 'sticky', top: 0, zIndex: 1 }"
            >
                <el-table-column prop="permissionId" label="ID" width="100" align="center" />
                <el-table-column prop="permissionCode" label="权限标识" min-width="220" />
                <el-table-column prop="permissionName" label="权限名称" min-width="180" />
                <el-table-column prop="permissionType" label="类型" width="140">
                    <template #default="{ row }">
                        <el-tag :type="typeTagMap[row.permissionType]">
                            {{ row.permissionType }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="上级权限" width="180">
                    <template #default="{ row }">
                        {{ getParentPermissionName(row.parentId) }}
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="更新时间" width="250" />
                <el-table-column label="操作" width="160" fixed="right" align="center">
                    <template #default="{ row }">
                        <div class="action-buttons">
                            <el-button link type="primary" @click="editPerm(row)">编辑</el-button>
                            <el-divider direction="vertical" />
                            <el-button link type="danger" @click="deletePerm(row.permissionId)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页器 -->
        <div class="pagination-wrapper">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[20, 50, 100, 200]"
                :total="totalItems"
                layout="total, sizes, prev, pager, next, jumper"
                background
                @current-change="handlePageChange"
                @size-change="handleSizeChange"
            />
        </div>

        <!-- 编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEditMode ? '编辑权限' : '新建权限'"
            width="600px"
            destroy-on-close
            class="custom-dialog"
        >
            <el-form :model="formData" label-width="100px" label-position="left">
                <el-form-item label="权限标识" required>
                    <el-input
                        v-model="formData.permissionCode"
                        placeholder="使用英文冒号分隔层级，如 system:user:manage"
                    />
                </el-form-item>
                <el-form-item label="权限名称" required>
                    <el-input v-model="formData.permissionName" />
                </el-form-item>
                <el-form-item label="权限类型" required>
                    <el-select v-model="formData.permissionType" placeholder="请选择类型">
                        <el-option
                            v-for="type in permissionTypes"
                            :key="type.value"
                            :label="type.label"
                            :value="type.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="上级权限">
                    <el-cascader
                        v-model="formData.parentId"
                        :options="permissionTree"
                        :props="{ value: 'permissionId', label: 'permissionName', checkStrictly: true }"
                        clearable
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus } from '@element-plus/icons-vue';
import { getPermissions, createPermission, updatePermission, deletePermission } from '@/api/permissionApi';

// 分页数据
const currentPage = ref(1);
const pageSize = ref(20);
const totalItems = ref(0);
const pageData = ref([]);
const searchKeyword = ref('');

// 对话框数据
const dialogVisible = ref(false);
const isEditMode = ref(false);
const formData = ref(initFormData());

// 类型配置
const typeTagMap = {
    system: '',
    menu: 'success',
    action: 'warning',
};

const permissionTypes = [
    { value: 'system', label: '系统权限' },
    { value: 'menu', label: '菜单权限' },
    { value: 'action', label: '操作权限' },
];

// 初始化表单
function initFormData() {
    return {
        permissionId: '',
        permissionCode: '',
        permissionName: '',
        permissionType: 'system',
        parentId: null,
        createTime: '',
    };
}

// 防抖搜索
let searchTimer = null;
const handleSearch = () => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
        currentPage.value = 1;
        loadData();
    }, 300);
};

// 加载数据
const loadData = async () => {
    try {
        const params = {
            page: currentPage.value,
            size: pageSize.value,
            search: searchKeyword.value,
        };
        const res = await getPermissions(params);
        pageData.value = res.data.content || [];
        totalItems.value = res.data.total || 0;
    } catch (error) {
        ElMessage.error('数据加载失败');
        console.error(error);
    }
};

// 权限树结构（示例数据）
const permissionTree = computed(() => {
    return pageData.value.map((p) => ({
        permissionId: p.permissionId,
        permissionName: p.permissionName,
        children: [],
    }));
});

// 获取上级权限名称
const getParentPermissionName = (parentId) => {
    const parent = pageData.value.find((item) => item.permissionId === parentId);
    return parent ? parent.permissionName : '无上级权限';
};

// 分页处理
const handlePageChange = () => loadData();
const handleSizeChange = () => {
    currentPage.value = 1;
    loadData();
};

// 打开对话框
const handleCreate = () => {
    isEditMode.value = false;
    formData.value = initFormData();
    dialogVisible.value = true;
};

const editPerm = (row) => {
    isEditMode.value = true;
    formData.value = { ...row };
    dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
    try {
        const api = isEditMode.value ? updatePermission : createPermission;
        await api(formData.value);
        ElMessage.success(isEditMode.value ? '修改成功' : '创建成功');
        dialogVisible.value = false;
        loadData();
    } catch (error) {
        ElMessage.error('操作失败');
        console.error(error);
    }
};

// 删除确认
const deletePerm = async (id) => {
    try {
        await ElMessageBox.confirm('此操作将永久删除该权限，是否继续？', '警告', {
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            type: 'warning',
            confirmButtonClass: 'el-button--danger',
            cancelButtonClass: 'el-button--text',
        });
        await deletePermission(id);
        ElMessage.success('删除成功');
        loadData();
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
        }
    }
};

// 初始化加载
onMounted(loadData);
</script>

<style scoped>
.container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #ffffff;
}

.header {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    padding: 10px 10px;
    border-bottom: 1px solid #e2e8f0;
    flex-shrink: 0;
}

.header-content {
    max-width: 1440px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 5px;
}

.title-section {
    display: flex;
    align-items: center;
    gap: 24px;
}

.page-title {
    font-size: 20px;
    font-weight: 600;
    color: #1e293b;
    margin: 0;
    letter-spacing: 0.5px;
}

.subtitle {
    color: #64748b;
    font-size: 14px;
}

.divider {
    width: 2px;
    height: 24px;
    background: #cbd5e1;
}

.action-group {
    display: flex;
    align-items: center;
    gap: 16px;
}

.search-input {
    width: 320px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.table-container {
    flex: 1;
    padding: 5px 0px;
    overflow-y: auto;
    background: #ffffff;
}

:deep(.el-table) {
    --el-table-border-color: #e2e8f0;
    --el-table-header-bg-color: #f8fafc;
    --el-table-row-hover-bg-color: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
}

:deep(.el-table th) {
    font-weight: 600;
    color: #475569;
}

:deep(.el-table td) {
    color: #475569;
}

.pagination-wrapper {
    padding: 16px 32px;
    background: rgba(255, 255, 255, 0.9);
    border-top: 1px solid #e2e8f0;
    flex-shrink: 0;
}

.action-buttons {
    display: flex;
    align-items: center;
    gap: 8px;
}

:deep(.custom-dialog) {
    border-radius: 12px;
    box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
}

:deep(.custom-dialog .el-dialog__header) {
    padding: 24px;
    border-bottom: 1px solid #e2e8f0;
    margin-right: 0;
}

:deep(.custom-dialog .el-dialog__body) {
    padding: 24px;
}

::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-thumb {
    background-color: #cbd5e1;
    border-radius: 8px;
    border: 2px solid transparent;
    background-clip: content-box;
}

::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 8px;
}
</style>